package collection;

import syn.Phone;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author ：黄淼淳
 * @description：线程安全的集合
 * @date ：2021/12/12 15:56
 */
public class SafeCollection {
    public static void main(String[] args) {
       listSafe();
//        setSafe();
//        mapSafe();
    }

    public static void mapSafe(){
        Map<String,String> map = new ConcurrentHashMap<>();
        for (int i = 0; i < 30; i++) {
            new Thread(()->{
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0,8));
                System.out.println(map);
            },String.valueOf(i)).start();
        }
    }

    public static void setSafe(){
        Set<String> set = new CopyOnWriteArraySet<>();
        for (int i = 0; i < 30; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(set);
            },String.valueOf(i)).start();
        }
    }


    public static void listSafe(){
        List<String> list;
        /*//线程不安全,但是效率更高
        //java.util.ConcurrentModificationException  并发修改异常
         list = new ArrayList<>();*/
        /*//线程安全，但是效率低
        list = new Vector<>();*/
        /*//创建线程安全的list集合
        list = Collections.synchronizedList(new ArrayList<>());*/
        //写时复制
        list = new CopyOnWriteArrayList<>();
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(list+Thread.currentThread().getName());
            }, String.valueOf(i)).start();
        }
    }





    public static void test1(){
        //线程不安全
        List<Integer> list = new ArrayList<>();
        list.add(12);
        //线程安全，但是效率低
        list = new Vector<>();
        list = Collections.synchronizedList(new ArrayList<>());

        //线程安全，写时复制
        list = new CopyOnWriteArrayList<>();
        list.add(12);

    }
}
